package com.woniuxy.kaer.commons.jwtUtil;



import com.woniuxy.kaer.redis.util.RedisKey;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import lombok.Data;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.security.Key;
import java.util.Date;
import java.util.Map;

//JWT工具类
@Component
@Data
public class JwtUtil {
    //自定义的秘钥
    //HS256：即字节长度>=32
    @Resource
    private  StringRedisTemplate stringRedisTemplate;
    static String sect ="ksaasfdasdfadsfwfrasdfsadffcasijfasadfasfdlkfjlasjflksajfd";
    //生成token
    //键值对包含用户信息
    //以分钟为单位的时间 代表jwt的有效时间
    public static String createToken(Map<String, Object> body, Integer mil) {
        Key key = Keys.hmacShaKeyFor(sect.getBytes());
        return Jwts.builder()
                .setClaims(body)
                .setExpiration(new Date(System.currentTimeMillis() + mil * 60 * 1000))
                .signWith(key)
                .compact();
    }
    //解析tokenlo
    public static Claims parseToken(String token) {
        Key key = Keys.hmacShaKeyFor(sect.getBytes());
        return Jwts.parserBuilder().setSigningKey(key)
                .build().parseClaimsJws(token).getBody();
    }

    public  Integer getUserId(String token){
        return Integer.parseInt(parseToken(stringRedisTemplate.opsForValue().get(RedisKey.REFRESH_ACCESS_EXPIRE(token))).get("managerId").toString());
    }
    public  Integer getFounderId(String token){
        return Integer.parseInt(parseToken(stringRedisTemplate.opsForValue().get(RedisKey.REFRESH_ACCESS_EXPIRE(token))).get("founderId").toString());
    }
    public  Integer getManagerId(String token){
        return Integer.parseInt(parseToken(stringRedisTemplate.opsForValue().get(RedisKey.REFRESH_ACCESS_EXPIRE(token))).get("managerId").toString());
    }
    public Integer getManagerId1(String token) {
        return parseToken(token).get("managerId", Integer.class);
    }


}
